from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.filters import SearchFilter
from rest_framework.viewsets import ModelViewSet
from myapp.models import *
from myapp.ser import Serstaff
from rest_framework.response import Response


#  分页器
class Pag(PageNumberPagination):
    page_size = 5
    max_page_size = 5


#  获取员工
class Show(ModelViewSet):
    queryset = Staff.objects.all()
    serializer_class = Serstaff
    #  分页
    pagination_class = Pag
     # 模糊查询
    filter_backends = [SearchFilter]
    search_fields = ['name', 'depart__d_name']


#  入职
class Submit(APIView):
    def post(self,request):
        name = request.data.get('name')
        depart = request.data.get('depart')
        staff = Staff.objects.create(name=name,role=2, depart_id=depart)
        staff.save()
        return Response({'code':200,'msg':'入职成功'})


#  加班申请
class Workovertime(APIView):
    def post(self,request):
        date = request.data.get('date')
        start = request.data.get('start')
        end = request.data.get('end')
        staff = request.data.get('staff')

        sta = Work.objects.create(date=date,start=start,end=end,role=0,staff_id=staff)
        sta.save()
        return Response({'code':200,'msg':'提交申请加班'})


 # 查看申请加班
class See(APIView):
    def get(self,request):
        depart_id = request.data.get('depart_id')
        sto = Staff.objects.filter(depart_id=depart_id,role=0).all()
        list1 = []
        for i in sto:
            work = Work.objects.filter(staff_id=i.id,role=0).all()
            for j in work:
                list1.append(j.id)
        list2 = []
        for i in list1:
            work = Work.objects.filter(id=i).first()
            sta = Staff.objects.filter(id=work.staff_id).first()
            list2.append({
                'name':sta.name,
                'date':work.date,
                'start':work.start,
                'end':work.end,
            })
        return Response({'code':200,'msg':'查看成功',"data":list2})


#  同意和不同意加班
class Agree(APIView):
    def put(self,request):
        w_id = request.data.get('id')
        role = request.data.get('role')

        if role == '0':
            work = Work.objects.filter(id=w_id).first()
            work.role = 0
            work.save()
            return Response({'code':200,'msg':'同意申请'})
        elif role == '1':
            work = Work.objects.filter(id=w_id).first()
            work.role = 1
            work.save()
            return Response({'code':400,'msg':'拒绝加班'})
        return Response({'code':201,'msg':'申请未生效'})





